package org.kinglone.back.voice.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.kinglone.back.voice.model.WeixinVoice;
import org.kinglone.back.voice.service.WeixinVoiceService;
import org.kinglone.utlis.Conversion;
import org.kinglone.utlis.DateUtils;
import org.kinglone.utlis.JSONMessageView;
import org.kinglone.utlis.PropertieUtil;
import org.kinglone.utlis.UUIDUtils;
import org.kinglone.weixin.kit.RefreshAccessTokenKit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/voice")
public class WeixinVoiceAction {
	private static final String download_url = "https://qyapi.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";  

	@Autowired
	private WeixinVoiceService weixinVoiceService;
	
	/**
	 * 微信上传语音，保存到自己服务器
	 * @param request
	 * @return
	 * @throws Exception
	 */
	//上传文件会自动绑定到MultipartFile中
    @RequestMapping(value="/uploadVoice.jspx",method=RequestMethod.POST)
    public JSONMessageView upload(HttpServletRequest request) throws Exception {
    	JSONMessageView msg = new JSONMessageView(-1, null, "上传失败!");
    	String jsonString = request.getParameter("res");//{"errMsg":"uploadVoice:ok","serverId":"1237378768e7q8e7r8qwesafdasdfasdfaxss111"}
    	JSONObject json = JSONObject.fromObject(jsonString);
    	String media_id = json.getString("serverId");
    	System.out.println("media_id:"+media_id);
    	String baseAccess_token = RefreshAccessTokenKit.refreshToken();
    	String url = download_url.replace("ACCESS_TOKEN", baseAccess_token).replace("MEDIA_ID", media_id); 
    	System.out.println("url:"+url);
    	InputStream is = null;  
    	String basepath=PropertieUtil.getValue("config.properties", "upload_url");
    	String relativePath="/upload/"+DateUtils.format(new Date(), "yyyyMMdd")+"/";
		String filePath = basepath+relativePath;
		String fileName = "weixinVoice"+UUIDUtils.getUUID();
		String suffix = ".amr";
		File file = new File(filePath);
		if(!file.exists()){
			file.mkdirs();
		}
    	try {  
            URL urlGet = new URL(url);  
            HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();  
            http.setRequestMethod("GET"); // 必须是get方式请求  
            http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");  
            http.setDoOutput(true);  
            http.setDoInput(true);  
            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒  
            System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒  
            http.connect();  
            // 获取文件转化为byte流  
            is = http.getInputStream();  
            BufferedInputStream bis = new BufferedInputStream(is);
			if (!filePath.endsWith("/")) {  			  
	             filePath += "/";  	  
	         } 
			FileOutputStream fileOut = new FileOutputStream(filePath +fileName+suffix);
			BufferedOutputStream bos = new BufferedOutputStream(fileOut);
			byte[] by = new byte[4096];
			int len = bis.read(by);
			while(len != -1){
				bos.write(by, 0, len);
				len = bis.read(by);
			}
			bos.close();  
	        bis.close();  
	        http.disconnect();
	        
	        /*File source = new File(filePath +fileName+suffix);
	        File target = new File(filePath+fileName+".mp3");*/
	        Conversion conversion = new Conversion();
	        Conversion.ToMp3(filePath +fileName, filePath+fileName);
	        
	           
	        
	        /*AudioAttributes audio = new AudioAttributes();
	        Encoder encoder = new Encoder();
	        audio.setCodec("libmp3lame");
	        EncodingAttributes attrs = new EncodingAttributes();
	        attrs.setFormat("mp3");
	        attrs.setAudioAttributes(audio);

	        try {
	        encoder.encode(source, target, attrs);
	        } catch (IllegalArgumentException e) {
	        e.printStackTrace();
	        } catch (InputFormatException e) {
	        e.printStackTrace();
	        } catch (EncoderException e) {
	        e.printStackTrace();
	        }
	     */   	        
	        String voiceUrl =relativePath +fileName+".mp3";
	        WeixinVoice v = new WeixinVoice();
	        v.setServiceId(media_id);
	        v.setUrl(voiceUrl);
	        v.setUserId(1);
	        weixinVoiceService.save(v);
	        msg.setMessage("文件保存成功!");
	        msg.setContent("/weixin"+voiceUrl);
	      //  msg.setContent("/weixin/upload/20180330/Kalimba.mp3");
	        msg.setCode(0);
	        System.out.println("msg:"+msg);
        } catch (Exception e) {  
            e.printStackTrace();
            msg.setCode(-1);
            msg.setMessage("文件保存失败!");	    
        }  
       return msg;  
    }
    /**
     * 微信上传图片，保存到自己的服务器
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/uploadImage.jspx",method=RequestMethod.POST)
    public JSONMessageView uploadImage(HttpServletRequest request) throws Exception {
    	JSONMessageView msg = new JSONMessageView(-1, null, "上传失败!");
    	String jsonString = request.getParameter("res");//{"errMsg":"uploadVoice:ok","serverId":"1237378768e7q8e7r8qwesafdasdfasdfaxss111"}
    	JSONObject json = JSONObject.fromObject(jsonString);
    	String media_id = json.getString("serverId");
    	System.out.println("media_id:"+media_id);
    	String baseAccess_token = RefreshAccessTokenKit.refreshToken();
    	String url = download_url.replace("ACCESS_TOKEN", baseAccess_token).replace("MEDIA_ID", media_id); 
    	System.out.println("url:"+url);
    	InputStream is = null;  
    	String basepath=PropertieUtil.getValue("config.properties", "upload_url");
    	String relativePath="/upload/"+DateUtils.format(new Date(), "yyyyMMdd")+"/";
    	String filePath = basepath+relativePath;
    	String fileName = "weixinVoice"+UUIDUtils.getUUID();
    	String suffix = ".jpg";
    	File file = new File(filePath);
    	if(!file.exists()){
    		file.mkdirs();
    	}
    	try {  
    		URL urlGet = new URL(url);  
    		HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();  
    		http.setRequestMethod("GET"); // 必须是get方式请求  
    		http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");  
    		http.setDoOutput(true);  
    		http.setDoInput(true);  
    		System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒  
    		System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒  
    		http.connect();  
    		// 获取文件转化为byte流  
    		is = http.getInputStream();  
    		BufferedInputStream bis = new BufferedInputStream(is);
    		if (!filePath.endsWith("/")) {  			  
    			filePath += "/";  	  
    		} 
    		FileOutputStream fileOut = new FileOutputStream(filePath +fileName+suffix);
    		BufferedOutputStream bos = new BufferedOutputStream(fileOut);
    		byte[] by = new byte[4096];
    		int len = bis.read(by);
    		while(len != -1){
    			bos.write(by, 0, len);
    			len = bis.read(by);
    		}
    		bos.close();  
    		bis.close();  
    		http.disconnect();
    		
    		String voiceUrl =relativePath +fileName+".jpg";
    		WeixinVoice v = new WeixinVoice();
    		v.setServiceId(media_id);
    		v.setUrl(voiceUrl);
    		v.setUserId(1);
    		weixinVoiceService.save(v);
    		msg.setMessage("文件保存成功!");
    		msg.setContent("/weixin"+voiceUrl);
    		msg.setCode(0);
    		System.out.println("msg:"+msg);
    	} catch (Exception e) {  
    		e.printStackTrace();
    		msg.setCode(-1);
    		msg.setMessage("文件保存失败!");	    
    	}  
    	return msg;  
    }
	
}